local service_discovery = require "service_discovery"
local http = require "resty.http"
local cjson = require "cjson"

local _M = {}

function _M.route()
    local args = ngx.req.get_uri_args()
    local path = ngx.var.uri
    
    -- 解析服务名和剩余路径
    local service_name, remaining_path, err = service_discovery.parse_request_path(path)
    if not service_name then
        ngx.log(ngx.ERR, "Failed to parse path: ", err)
        ngx.exit(ngx.HTTP_BAD_REQUEST)
        return
    end
    
    ngx.log(ngx.INFO, "Routing request for service: ", service_name, ", path: ", remaining_path)
    
    -- 选择健康的后端
    local backend_url, err = service_discovery.select_backend(service_name)
    if not backend_url then
        ngx.log(ngx.ERR, "No backend available: ", err)
        ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
        return
    end
    
    ngx.log(ngx.INFO, "Selected backend: ", backend_url)
    
    -- 构建目标URL
    local target_url = backend_url .. path
    if next(args) then
        target_url = target_url .. "?" .. ngx.encode_args(args)
    end
    
    -- 转发请求
    local httpc = http.new()
    httpc:set_timeout(5000)  -- 5秒超时
    
    -- 获取原始请求方法、头信息和body
    local method = ngx.req.get_method()
    local headers = ngx.req.get_headers()
    local body_data = nil
    
    -- 读取请求体（如果是POST/PUT等方法）
    if method == "POST" or method == "PUT" then
        ngx.req.read_body()
        body_data = ngx.req.get_body_data()
    end
    
    -- 转发请求到后端服务
    local res, err = httpc:request_uri(target_url, {
        method = method,
        body = body_data,
        headers = headers,
        ssl_verify = false
    })
    
    if not res then
        ngx.log(ngx.ERR, "Failed to request backend: ", err)
        ngx.exit(ngx.HTTP_BAD_GATEWAY)
        return
    end
    
    -- 设置响应
    ngx.status = res.status
    
    -- 转发响应头（过滤掉一些不需要的头）
    for key, value in pairs(res.headers) do
        if key ~= "transfer-encoding" and key ~= "connection" then
            ngx.header[key] = value
        end
    end
    
    -- 添加一些调试头信息
    ngx.header["X-Backend-URL"] = target_url
    ngx.header["X-Service-Name"] = service_name
    
    -- 返回响应体
    ngx.say(res.body)
end

return _M